from django.db import transaction
from rest_framework import serializers

from apps.spit.models import Spit


class SpitSerialzier(serializers.ModelSerializer):

    class Meta:
        model = Spit
        fields = '__all__'

    @transaction.atomic
    def create(self, validated_data):
        spit = super().create(validated_data)
        try:
            user = self.context["request"].user
        except:
            user = None
        if spit.parent:
            if user and user.is_authenticated():
                spit.userid = user.id
                spit.nickname = user.nickname if user.nickname else user.username
                # spit.avatar = user.avatar
                spit.save()
                spit.parent.comment += 1
                spit.parent.save()
                return spit
            else:
                raise serializers.ValidationError('用户未登录')

        else:
            return spit